<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
  <head>
    <title>Scheduler Job Page</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <link href="${this.request.contextPath}/.resources/admin-css/admin-all.css" type="text/css" rel="stylesheet" />
    <link href="${this.request.contextPath}/.resources/scheduler/css/styles.css" type="text/css" rel="stylesheet" />
    <link href="${this.request.contextPath}/.resources/calendar/calendar-green.css" type="text/css" rel="stylesheet" />
    <script src="${this.request.contextPath}/.magnolia/pages/javascript.js" type="text/javascript"></script>
    <script src="${this.request.contextPath}/.resources/js-classes/mgnl/scheduler/date.js" type="text/javascript"></script>
    <script src="${this.request.contextPath}/.resources/scheduler/js/codepress/codepress.js" type="text/javascript"></script>
    <script src="${this.request.contextPath}/.resources/calendar/calendar_stripped.js" type="text/javascript"></script>
    <script src="${this.request.contextPath}/.resources/calendar/lang/calendar-en.js" type="text/javascript"></script>
    <script src="${this.request.contextPath}/.resources/calendar/calendar-setup_stripped.js" type="text/javascript"></script>
  </head>
  <body id="mgnl">
    <form method="post" action="" enctype="multipart/form-data">
      <div class="pageframe">
      	<input type="hidden" id="uuid" name="uuid" value="${this.UUID!''}" />
        <h3>Job Editor</h3>
        
        [#if message?exists]
	        [#if ctx.exception?exists]
	      		<div class="error">${message}</div>
	      	[#else]
      			<div class="success">${message}</div>
      		[/#if]
      	[/#if]
      	      	
      	[#if this.newJobDefinition]
      	    [#if !message?exists]
      	    <div id="infoMsg" class="info">
      	    Job creation allows you to choose between <em>Command</em> and <em>Groovy</em> jobs. Up to 10 optional parameters for each job can be added.
      	    Empty parameters (either key or value or both) will be automatically discarded.
      	    Fields marked by <strong>*</strong> are mandatory. Job name must be unique.
      	    If you set your job as active, a start time must be entered. You can set a different start time as long as the job has not run yet.
      	    Once it has run, start time cannot be changed. At anytime you can edit your job. E.g. you can set a different cron expression or 
      	    temporarily (de)activate it or set an end time. 
      	    </div>
      	    [/#if]
      		<input type="hidden" id="command" name="command" value="createJob" />
      		<div class="formelement">
      			<label for="name">Name *</label>
      			<input type="text" name="jobName" value="${this.jobName!''}"/>
      		</div>
      		<div class="formelement">
      			<label for="description">Description</label>
      			<textarea id="description" name="description" rows="2" cols="100" style="width: 800px">${this.description!''}</textarea>
      		</div>
      		<br/>
      		<br/>
      		<div class="formelement">
      			<input type="hidden" id="jobType" name="jobType" value="${this.jobType!'groovyJob'}" />
	   			<label for="jobType">Job type</label>
      			<select name="jobType" onchange="setJobType(this)">
	      			<option value="commandJob">Command</option>
	      			<option value="groovyJob" selected="selected">Groovy</option>
      			</select>
      		</div>
      		<br/>
      		<div id="groovyStuff"  style="">
      		<div class="formelement">
		          <label for="mgnlFileImport">Upload groovy script</label>
		          <input type="file" name="mgnlFileImport" />
		          <input type="submit" value="Upload" onclick="uploadFile()" class="mgnlControlButton" />
		    </div>
	        <br/>
	        <div class="formelement" style="height: auto">
	          <label for="groovyScriptTxtArea">Groovy script *</label>
	          <textarea id="groovyScriptTxtArea" name="groovyScriptTxtArea" rows="20" cols="120" style="width: 800px" class="codepress groovy readonly-off">${this.groovyScript!''}</textarea>
	          <input type="hidden" name="groovyScript" id="groovyScript" value="${this.groovyScript!''}"/>
	        </div>
	        </div>
	        <br/>
     		<div id="catalogCommand" class="formelement" style="display: none">
   			<label for="command">Catalog/Command *</label>
	   			<input type="hidden" id="catalog" name="catalog" value=""/>
	   			<select id="commandName" name="commandName">
	   			[#list this.commands?keys as catalog]
	   			    <optgroup id="${catalog}" label="${catalog}">
	   			    [#list this.commands[catalog] as commandName]
	   					<option value="${commandName}">${commandName}</option>
	   				[/#list]      			    
	   			    </optgroup>
	   			[/#list]
	   			</select>
     		</div>
      		<input type="hidden" name="jobParams" id="jobParams" value="" />
      			<div  class="formelement" style="height: auto">
	   			<label for="paramsContainer">Job parameters</label>
	   			<ol id="paramsContainer" style="list-style: none;">
	   			[#list this.jobParams?keys as key]
	   			    <li style="margin-bottom: 4px">
	   				<span id="key_${key}" class="paramKey" style="${(key_index == 0)?string('margin-left:0', '')}"><strong>${key}</strong></span>
	   				<input type="text" id="jobparam_${key_index}" name="${key}" value="${this.jobParams[key]}"/>
	   				<a class="removeLink" onclick="this.parentNode.parentNode.removeChild(this.parentNode);">Remove</a>
	   				<li>
      			[/#list]
      			</ol>
      			<br/>
      			<input type="button" value="Add Parameter" onclick="addField('paramsContainer','jobparam_',10);" class="mgnlControlButton" style="margin-left: 200px"/>
	      		</div>
      		    <br/>
	      		<div class="formelement">
	   			<label for="daStartTime">Start time</label>
      			<input type="hidden" id="startTime" name="startTime" value="${this.startTime?c}"/>
      			<input type="hidden" id="initialStartTime" name="initialStartTime" value="${this.startTime?c}"/>
      			<span id="daStartTime" style="float:left; width:220px; font-weight: bold">Click to choose a start time</span>
      			<img id="triggerStart" src="${this.request.contextPath}/.resources/scheduler/css/images/date.png" style="cursor: pointer;"/>
      			<script type="text/javascript">
      			  var start = new Date() 
      			  var startVal = document.getElementById('startTime').value
    			  if(startVal != 0){
        			start.setTime(startVal)  
      			    document.getElementById('daStartTime').innerHTML = start.format( 'dd MMM yyyy, HH:mm:ss') 
        		  }
				  Calendar.setup(
				    {
				      inputField  : "startTime",
				      displayArea  : "daStartTime",
				      button      : "triggerStart",
				      ifFormat    : "%s",
				      daFormat    : "%d %B, %Y %H:%M:00",
				      showsTime   : true,
				      date        : start
				    }
				  );
				</script>
				</div>
	      		<br/>
	      		<div class="formelement">
	   			<label for="jobParams">End time</label>
      			<span id="daEndTime" style="float:left; width:220px; font-weight: bold">Click to choose an end time</span>
      			<input type="hidden" id="endTime" name="endTime" value="${this.endTime?c}"/>
      			<input type="hidden" id="initialEndTime" name="initialEndTime" value="${this.endTime?c}"/>
  				<img id="triggerEnd" src="${this.request.contextPath}/.resources/scheduler/css/images/date.png" style="cursor: pointer;"/> 
      			<script type="text/javascript">
      			var end = new Date() 
    			  var endVal = document.getElementById('endTime').value
  			  	  if(endVal != 0){
      				end.setTime(endVal)  
       			    document.getElementById('daEndTime').innerHTML = end.format( 'dd MMM yyyy, HH:mm:ss') 
      		  	  }
				  Calendar.setup(
				    {
				      displayArea  : "daEndTime",   
				      inputField  : "endTime",   
				      ifFormat    : "%s", 
				      daFormat    : "%d %B, %Y %H:%M:%S", 
				      button      : "triggerEnd",
				      showsTime   : true,
				      date        : end
				    }
				  );
				</script>
				</div>
				<br/>	
      	[#elseif this.editJobDefinition]
      	    [#if !message?exists]
      		<div id="infoMsg" class="info">
      	    Fields marked by <strong>*</strong> are mandatory. 
      	    Up to 10 optional parameters for each job can be added. <strong>Empty parameters (either key or value or both) will be automatically removed.</strong>
      	    If you set your job as active, a start time must be entered. You can set a different start time as long as the job has not run yet.
      	    Once it has run, start time cannot be changed. At anytime you can edit your job. E.g. you can set a different cron expression or 
      	    temporarily (de)activate it or set an end time. 
      	    </div>
      	    [/#if]
      		<input type="hidden" id="command" name="command" value="updateJob" />
      		<div class="formelement">
      			<label for="name">Name</label>
      			<span id="name"><strong>${this.jobName}</strong></span>
      			<input type="hidden" name="jobName" value="${this.jobName}"/>
      		</div>
      		<div class="formelement">
      			<label for="description">Description</label>
      			<textarea id="description" name="description" rows="2" cols="100" style="width: 800px">${this.description!''}</textarea>
      		</div>
      		<br/>
      		<br/>
      		[#if !this.commandName?has_content]
      			<div class="formelement">
		          <label for="mgnlFileImport">Upload groovy script</label>
		          <input type="file" name="mgnlFileImport" />
		          <input type="submit" value="Upload" onclick="uploadFile()" class="mgnlControlButton" />
		        </div>
		        <br/>
		        <div class="formelement" style="height: auto">
		          <label for="groovyScriptTxtArea">Groovy script *</label>
		          <textarea id="groovyScriptTxtArea" name="groovyScriptTxtArea" rows="20" cols="120" style="width: 800px" class="codepress groovy readonly-off">${this.groovyScript!''}</textarea>
		          <input type="hidden" name="groovyScript" id="groovyScript" value="${this.groovyScript!''}"/>
		        </div>
		        <br/>
      		[#else]
      		    <br />
      		    <div class="formelement">
	   			<label for="command">Catalog/Command *</label>
      			<input type="hidden" id="catalog" name="catalog" value="${this.catalog}"/>
      			<select id="commandName" name="commandName">
      			[#list this.commands?keys as catalog]
      			    <optgroup id="${catalog}" label="${catalog}">
      			    [#list this.commands[catalog] as commandName]
      					<option value="${commandName}" ${(this.catalog== catalog && this.commandName == commandName)? string('selected=\'selected\'', '')}>${commandName}</option>
      				[/#list]      			    
      			    </optgroup>
      			[/#list]
      			</select>
      			</div>
      			<br />
      			<br />
      		[/#if]
	   			<input type="hidden" name="jobParams" id="jobParams" value="" />
      			<div  class="formelement" style="height: auto">
	   			<label for="paramsContainer">Job parameters</label>
	   			<ol id="paramsContainer" style="list-style: none;">
	   			[#list this.jobParams?keys as key]
	   			    <li style="margin-bottom: 4px">
	   				<span id="key_${key}" class="paramKey" style="${(key_index == 0)?string('margin-left:0', '')}"><strong>${key}</strong></span>
	   				<input type="text" id="jobparam_${key_index}" name="${key}" value="${this.jobParams[key]}"/>
	   				<a class="removeLink" onclick="this.parentNode.parentNode.removeChild(this.parentNode);">Remove</a>
	   				<li>
      			[/#list]
      			</ol>
      			<br />
      			<input type="button" value="Add Parameter" onclick="addField('paramsContainer','jobparam_',10);" class="mgnlControlButton" style="margin-left: 200px"/>
	      		</div>
	      		<br/>
	      		<div class="formelement">
	   			<label for="daStartTime">Start time</label>
      			<input type="hidden" id="startTime" name="startTime" value="${this.startTime?c}"/>
      			<input type="hidden" id="initialStartTime" name="initialStartTime" value="${this.startTime?c}"/>
      			<span id="daStartTime" style="float:left; width:220px; font-weight: bold">Click to choose a start time</span>
      			<!--  you cant set a new start time when the trigger has already started -->
      			[#if this.nextFireTime == 0] 
      				<img id="triggerStart" src="${this.request.contextPath}/.resources/scheduler/css/images/date.png" style="cursor: pointer;"/>
      			[/#if] 
      			<script type="text/javascript">
      			  var start = new Date() 
      			  var startVal = document.getElementById('startTime').value
    			  if(startVal != 0){
        			start.setTime(startVal)  
      			    document.getElementById('daStartTime').innerHTML = start.format( 'dd MMM yyyy, HH:mm:ss') 
        		  }
      			[#if this.nextFireTime == 0] 
				  Calendar.setup(
				    {
				      inputField  : "startTime",
				      displayArea  : "daStartTime",
				      button      : "triggerStart",
				      ifFormat    : "%s",
				      daFormat    : "%d %B, %Y %H:%M:00",
				      showsTime   : true,
				      date        : start
				    }
				  );
				[/#if]  
				</script>
				</div>
	      		<br/>
	      		<div class="formelement">
	   			<label for="daEndTime">End time</label>
      			<span id="daEndTime" style="float:left; width:220px; font-weight: bold">Click to choose an end time</span>
      			<input type="hidden" id="endTime" name="endTime" value="${this.endTime?c}"/>
  				<input type="hidden" id="initialEndTime" name="initialEndTime" value="${this.endTime?c}"/>
  				<img id="triggerEnd" src="${this.request.contextPath}/.resources/scheduler/css/images/date.png" style="cursor: pointer;"/> 
      			<script type="text/javascript">
      			var end = new Date() 
    			  var endVal = document.getElementById('endTime').value
  			  	  if(endVal != 0){
      				end.setTime(endVal)  
       			    document.getElementById('daEndTime').innerHTML = end.format( 'dd MMM yyyy, HH:mm:ss') 
      		  	  }
				  Calendar.setup(
				    {
				      displayArea  : "daEndTime",   
				      inputField  : "endTime",   
				      ifFormat    : "%s", 
				      daFormat    : "%d %B, %Y %H:%M:%S", 
				      button      : "triggerEnd",
				      showsTime   : true,
				      date        : end
				    }
				  );
				</script>
				</div>
				<br/>
      	[#elseif this.deleteJobDefinition]
      		<input type="button" id="ok" value="OK" onclick="MgnlAdminCentral.showContent('/.magnolia/pages/schedulerJobList.html', false, false)" class="mgnlControlButton" />
      	[/#if]
      	[#if !this.deleteJobDefinition]
	      	<div class="formelement">
	   			<label for="cron">Cron expression *</label>
	   			<input type="text" id="cron" name="cron" value="${this.cron!''}"/>
	      	</div>
	      	<br/>
	      	<div class="formelement">
	   			<label for="active">Active</label>
	   			<input type="checkbox" id="active" name="active" ${this.active?string('checked=\'checked\'', '')}/>
	      	</div>
	      	<div id="buttons">
	        	<input type="submit" id="save" value="Save" onclick="warnBeforeSubmit(); return false" class="mgnlControlButton" />
	        	<input type="button" id="cancel" value="Cancel" onclick="MgnlAdminCentral.showContent('/.magnolia/pages/schedulerJobList.html', false, false)" class="mgnlControlButton" style="margin-left: 5px"/>
	        	<!-- 
	        	[#if !this.newJobDefinition]
	        		<input type="button" id="delete" value="Delete" onclick="deleteJob(); return false" class="mgnlControlButton" style="margin-left: 5px"/>
	        	[/#if]
	        	-->
	        </div>
      [/#if]
      </div>
    </form>
    
      <script type="text/javascript">
        function uploadFile(){
          document.getElementById('command').value='loadGroovyScript'
          document.forms[0].submit()  
        }

        function setCatalog(el){
        	catalogValue = el.options[el.selectedIndex].parentNode.label
        	document.getElementById('catalog').value=catalogValue
        }
        
        function setJobType(el){
        	type = el.options[el.selectedIndex].value
        	document.getElementById('jobType').value=type
        	if(type=='groovyJob'){
        		document.getElementById('catalogCommand').style.display='none'
        		document.getElementById('groovyStuff').style.display=''
        	} else {
        		document.getElementById('groovyStuff').style.display='none'
            	document.getElementById('catalogCommand').style.display=''
            	document.getElementById('groovyScriptTxtArea').value = ''	
                alert(document.getElementById('groovyScriptTxtArea').value)	
        	}		
        }
        
        function warnBeforeSubmit(){
          if(confirm('Are you sure, you want to save this job?')){
                //console.log(groovyScriptTxtArea.getCode())
                if(document.getElementById('groovyScript') != null)
                	document.getElementById('groovyScript').value = groovyScriptTxtArea.getCode()
                	
                document.getElementById('save').disabled=true
                /* all this stuff is needed because dynarch calendar returns
                the chosen datetime in seconds whereas the application needs it in ms, 
                so I need a way to check whether the user
                actually changed its value and, if so, multiply it by 1000*/ 
                st = document.getElementById('startTime')
                if(document.getElementById('initialStartTime').value != st.value)
                	st.value = st.value * 1000
                et = document.getElementById('endTime')
                if(et.value != 0 && (document.getElementById('initialEndTime').value != et.value))
                	et.value = et.value * 1000
				if(document.getElementById('commandName')!=null)
                	setCatalog(document.getElementById('commandName'))	
                getJobParameters()
                document.forms[0].submit()  
          }
            else
                return false    
        }
        
        function getJobParameters(){
        	var c = document.getElementById("paramsContainer")
        	var params = c.getElementsByTagName("input")
        	var s = ''            	 
			for(i = 0; i < params.length; ++i){
				//this is a new parameter
				if(params[i].name.indexOf('key_') == 0){
					keyName = params[i].value
					//get the bound value
					paramValue = params[i + 1].value
					if(keyName.length == 0 || paramValue.length == 0) {
						i++;
						continue
					}
					s += keyName  + ':' + paramValue
					//skip the next input field
					i++
				} else {
					if(params[i].value.length == 0) continue
					s += params[i].name  + ':' + params[i].value
				}
				if(i != (params.length - 1)) s += ';'
			}
			document.getElementById("jobParams").value = s
        }

        /*
        	Add more fields dynamically.
       		This was taken here http://www.openjs.com/scripts/examples/addfield.php
        	and modified to suit my needs
        */ 
        function addField(area,field,limit) {
        	if(!document.getElementById) return //Prevent older browsers from getting any further.
        	var field_area = document.getElementById(area)
        	var all_inputs = field_area.getElementsByTagName("input")
        	var last_item = all_inputs.length - 1
        	var last = 0
        	var count = 0
        	if(last_item >= 0) {
        		last = all_inputs[last_item].id
        		count = Number(last.split("_")[1]) + 1
        	} 
        	
        	//If the maximum number of elements have been reached, exit the function.
        	//		If the given limit is lower than 0, infinite number of fields can be created.
        	if(count > limit && limit > 0) return
         	
       		var li = document.createElement("li")
       		var input = document.createElement("input")
       		input.id = field+count
       		input.name = field+count
       		input.type = "text"
       		var key = document.createElement("input")
       		key.id = 'key_' + field+count;
       		key.name = 'key_' + field+count;
       		key.type = "text"
       		key.className = "paramKey"
           	if(count==0)
               	key.style.marginLeft='0'	
       	    var remove = document.createElement("a")
       	    remove.onclick= function () {this.parentNode.parentNode.removeChild(this.parentNode)}
           	remove.innerHTML = 'Remove'    
           	remove.className = 'removeLink'    
           	remove.style.marginLeft = '4px'    
       		li.appendChild(key)
       		li.appendChild(input)
       		li.appendChild(remove)        		
       		field_area.appendChild(li)
        }

        function deleteJob(){
           	if(confirm("Beware, this operation cannot be undone.\nAre you sure, you want to permanently delete this job?")){
               	uuid = document.getElementById('uuid').value
               	document.getElementById('command').value = 'deleteJob'
               	document.forms[0].submit()     	               	
           	}
        }             
      </script>
  </body>
</html>